package com.example.springbootshiro.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * <p>
 *
 * </p>
 *
 * @author gqz
 * @version 1.0
 * @since 2021/9/2:15:44
 */
@Controller
@RequestMapping("/shiro")
@Slf4j
public class ShiroController {
    @RequestMapping("/index")
    public String indexPage()
    {
        return "index";
    }

    @RequestMapping("/add")
    public String add()
    {
        return "user/add";
    }

    @RequestMapping("/update")
    public String update()
    {
        return "user/update";
    }

    @RequestMapping("/loginPage")
    public String loginPage()
    {
        return "login";
    }


    @PostMapping("/login")
    public String login(String username,String password)
    {
        Subject subject = SecurityUtils.getSubject();
        if (!subject.isAuthenticated())
        {
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            //设置记住我
            token.setRememberMe(true);
            //执行登陆的方法,如果没有异常,就说明ok了
            try{
                subject.login(token);
                return "index";
            }catch (UnknownAccountException e)
            {
              log.error("用户名不存在");
              return "login";
            }catch (IncorrectCredentialsException e)
            {
                log.error("密码错误");
                return "login";
            }
        }
        return "index";
    }
    @ResponseBody
    @RequestMapping("/noauth")
    public String noauth()
    {
        return "未经授权,无法访问此页面";
    }
}
